package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.dto.DeptDTO;
import com.ktjy.pojo.SysDept;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ISysDeptService;
import com.ktjy.utils.AjaxResult;
import com.ktjy.utils.Constants;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-07-29
 */
@RestController
@RequestMapping("/api/sys/dept")
public class SysDeptController {
    Logger log= LoggerFactory.getLogger(SysDeptController.class);

    @Resource
    ISysDeptService sysDeptService;

    @RequestMapping("/list")
    public AjaxResult list(DeptDTO deptDTO){
        List<SysDept> list = sysDeptService.findList(deptDTO);
        return AjaxResult.success(list);
    }

    @GetMapping("/treeselect")
    public AjaxResult treeselect() {
        List<SysDept> list = sysDeptService.list();
        List<SysDept> depts = sysDeptService.buildTree(list,0l);
        return AjaxResult.success(depts);
    }

    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody SysDept sysDept){
        try {
            boolean ok=sysDeptService.saveOrUpdate(sysDept);
            if(ok){
                return AjaxResult.success("保存成功");
            }
        } catch (Exception e) {
            log.error("SysDeptController中saveOrUpdate方法执行报错的。",e);
        }
        return AjaxResult.error("保存失败");
    }

    @GetMapping("/view/{id}")
    public AjaxResult view(@PathVariable("id") Long id){
        //查询用户详情
        try {
            SysDept sysDept=sysDeptService.getById(id);
            if(sysDept!=null){
                return AjaxResult.success(sysDept);
            }
        } catch (Exception e) {
            log.error("SysDeptController中edit方法执行报错的。",e);
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/del/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            boolean ok= sysDeptService.removeById(id);
            if(ok){//删除成功
                return AjaxResult.success("删除成功");
            }
        } catch (Exception e) {
            log.error("SysDeptController中del方法执行报错的。",e);
        }
        return AjaxResult.error("删除失败");
    }

    @GetMapping("/checkNameUnique")
    public AjaxResult checkNameUnique(@RequestParam("name") String name){
        try {
            boolean ok = sysDeptService.checkNameUnique(name);
            if(!ok){//数据库不存在该账号
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("SysDeptController中checkNameUnique方法执行报错的。",e);
        }
        return AjaxResult.error();
    }
}
